package com.example.hrsystem.ui.attendance;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.AttendanceRecord;
import com.example.hrsystem.data.source.AppDatabase;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 打卡Fragment
 * 用于员工签到、签退操作，显示当前时间和位置信息
 */
public class AttendanceFragment extends Fragment {

    private TextView currentTimeTextView;
    private TextView checkInTimeTextView;
    private TextView checkOutTimeTextView;
    private TextView currentLocationTextView;
    private Button checkInButton;
    private Button checkOutButton;

    private FusedLocationProviderClient fusedLocationClient;
    private boolean isCheckedIn = false;
    private boolean isCheckedOut = false;
    private Handler handler = new Handler(Looper.getMainLooper());
    private AttendanceViewModel attendanceViewModel;
    private AppDatabase database;
    private String currentEmployeeId; // 登录用户的员工ID
    private SharedPreferences sharedPreferences;
    private String prefsName; // 基于用户ID的SharedPreferences名称
    private static final String KEY_CHECKED_IN = "checked_in";
    private static final String KEY_CHECKED_OUT = "checked_out";
    private static final String KEY_CHECK_IN_TIME = "check_in_time";
    private static final String KEY_CHECK_OUT_TIME = "check_out_time";
    private static final String KEY_CURRENT_DATE = "current_date";

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_attendance, container, false);

        // 初始化UI组件
        initViews(view);

        // 初始化数据库
        if (getActivity() != null) {
            database = AppDatabase.getDatabase(getActivity().getApplicationContext());
            
            // 获取登录用户信息
            SharedPreferences userPrefs = getActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
            currentEmployeeId = userPrefs.getString("employee_id", "1001"); // 默认值仅用于开发测试
            
            // 创建基于用户ID的SharedPreferences名称，确保数据隔离
            prefsName = "attendance_prefs_" + currentEmployeeId;
            sharedPreferences = getActivity().getSharedPreferences(prefsName, Context.MODE_PRIVATE);
        }

        // 初始化ViewModel
        attendanceViewModel = new ViewModelProvider(this).get(AttendanceViewModel.class);

        // 初始化位置服务
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());

        // 恢复打卡状态
        restoreAttendanceState();

        // 从数据库加载今日打卡记录
        loadTodayAttendanceRecord();

        // 更新当前时间
        updateCurrentTime();

        // 获取当前位置
        getCurrentLocation();

        // 设置打卡按钮点击事件
        setupCheckInOutButtons();

        return view;
    }

    /**
     * 从SharedPreferences恢复打卡状态
     */
    private void restoreAttendanceState() {
        try {
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
            String savedDate = sharedPreferences.getString(KEY_CURRENT_DATE, "");
            
            // 只有当天的打卡状态才有效
            if (currentDate.equals(savedDate)) {
                isCheckedIn = sharedPreferences.getBoolean(KEY_CHECKED_IN, false);
                isCheckedOut = sharedPreferences.getBoolean(KEY_CHECKED_OUT, false);
                
                // 恢复UI状态
                if (isCheckedIn) {
                    String checkInTime = sharedPreferences.getString(KEY_CHECK_IN_TIME, "");
                    checkInTimeTextView.setText("签到时间：" + checkInTime);
                    checkInTimeTextView.setVisibility(View.VISIBLE);
                    checkInButton.setText(isCheckedOut ? "今日已完成打卡" : "已签到");
                    checkInButton.setEnabled(false);
                    
                    if (isCheckedOut) {
                        checkInButton.setBackgroundResource(R.drawable.button_secondary);
                    }
                    
                    checkOutButton.setEnabled(!isCheckedOut);
                }
                
                if (isCheckedOut) {
                    String checkOutTime = sharedPreferences.getString(KEY_CHECK_OUT_TIME, "");
                    checkOutTimeTextView.setText("签退时间：" + checkOutTime);
                    checkOutTimeTextView.setVisibility(View.VISIBLE);
                    checkOutButton.setText("已签退");
                    checkOutButton.setEnabled(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存打卡状态到SharedPreferences
     */
    private void saveAttendanceState() {
        try {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
            
            editor.putString(KEY_CURRENT_DATE, currentDate);
            editor.putBoolean(KEY_CHECKED_IN, isCheckedIn);
            editor.putBoolean(KEY_CHECKED_OUT, isCheckedOut);
            
            if (isCheckedIn) {
                String checkInText = checkInTimeTextView.getText().toString().replace("签到时间：", "");
                editor.putString(KEY_CHECK_IN_TIME, checkInText);
            }
            
            if (isCheckedOut) {
                String checkOutText = checkOutTimeTextView.getText().toString().replace("签退时间：", "");
                editor.putString(KEY_CHECK_OUT_TIME, checkOutText);
            }
            
            editor.apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从数据库加载今日打卡记录
     */
    private void loadTodayAttendanceRecord() {
        if (database != null) {
            // 异步查询今日打卡记录
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        AttendanceRecord record = database.attendanceDao().getTodayAttendanceRecordSync(currentEmployeeId);
                        if (record != null) {
                            updateUIWithRecord(record);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /**
     * 根据数据库记录更新UI
     */
    private void updateUIWithRecord(final AttendanceRecord record) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (record != null) {
                        // 更新签到状态
                        isCheckedIn = true;
                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
                        String checkInTime = sdf.format(record.getCheckInTime());
                        checkInTimeTextView.setText("签到时间：" + checkInTime);
                        checkInTimeTextView.setVisibility(View.VISIBLE);
                        checkInButton.setText("已签到");
                        checkInButton.setEnabled(false);
                        
                        // 更新签退状态
                        if (record.getCheckOutTime() != null) {
                            isCheckedOut = true;
                            String checkOutTime = sdf.format(record.getCheckOutTime());
                            checkOutTimeTextView.setText("签退时间：" + checkOutTime);
                            checkOutTimeTextView.setVisibility(View.VISIBLE);
                            checkOutButton.setText("已签退");
                            checkOutButton.setEnabled(false);
                            
                            // 签退后将签到按钮状态更新为"今日已完成打卡"
                            checkInButton.setText("今日已完成打卡");
                            checkInButton.setBackgroundResource(R.drawable.button_secondary);
                        } else {
                            checkOutButton.setEnabled(true);
                        }
                        
                        // 保存状态到SharedPreferences
                        saveAttendanceState();
                    }
                }
            });
        }
    }

    /**
     * 初始化UI组件
     */
    private void initViews(View view) {
        currentTimeTextView = view.findViewById(R.id.current_time_text_view);
        checkInTimeTextView = view.findViewById(R.id.check_in_time_text_view);
        checkOutTimeTextView = view.findViewById(R.id.check_out_time_text_view);
        currentLocationTextView = view.findViewById(R.id.current_location_text_view);
        checkInButton = view.findViewById(R.id.check_in_button);
        checkOutButton = view.findViewById(R.id.check_out_button);

        // 初始状态下，签退按钮不可用
        checkOutButton.setEnabled(false);
    }

    /**
     * 更新当前时间
     * 每秒更新一次时间显示
     */
    private void updateCurrentTime() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                // 获取当前时间
                Calendar calendar = Calendar.getInstance();
                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(calendar.getTime());
                currentTimeTextView.setText(currentTime);

                // 每秒更新一次
                handler.postDelayed(this, 1000);
            }
        });
    }

    /**
     * 获取当前位置
     * 需要获取位置权限
     */
    private void getCurrentLocation() {
        // 检查位置权限
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 请求位置权限
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            return;
        }

        // 获取当前位置
        fusedLocationClient.getLastLocation()
                .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location != null) {
                            // 位置获取成功，显示位置信息
                            double latitude = location.getLatitude();
                            double longitude = location.getLongitude();
                            currentLocationTextView.setText("当前位置：纬度 " + latitude + "，经度 " + longitude);
                        } else {
                            // 位置获取失败，显示默认信息
                            currentLocationTextView.setText("当前位置：无法获取位置信息");
                        }
                    }
                })
                .addOnFailureListener(getActivity(), new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        // 位置获取失败，显示错误信息
                        currentLocationTextView.setText("当前位置：获取位置失败");
                    }
                });
    }

    /**
     * 设置打卡按钮点击事件
     */
    private void setupCheckInOutButtons() {
        // 签到按钮点击事件
        checkInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isCheckedIn) {
                    // 执行签到操作
                    performCheckIn();
                } else if (isCheckedOut) {
                    // 已经完成签到和签退
                    Toast.makeText(getActivity(), "您今天已完成打卡", Toast.LENGTH_SHORT).show();
                } else {
                    // 已经签到但未签退
                    Toast.makeText(getActivity(), "您今天已经签到，请完成签退", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 签退按钮点击事件
        checkOutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isCheckedOut && isCheckedIn) {
                    // 执行签退操作
                    performCheckOut();
                } else if (!isCheckedIn) {
                    // 尚未签到，显示提示
                    Toast.makeText(getActivity(), "请先完成签到", Toast.LENGTH_SHORT).show();
                } else {
                    // 已经签退，显示提示
                    Toast.makeText(getActivity(), "您今天已经签退", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 执行签到操作
     */
    private void performCheckIn() {
        // 获取当前时间作为签到时间
        Date now = new Date();
        String checkInTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(now);
        checkInTimeTextView.setText("签到时间：" + checkInTime);
        checkInTimeTextView.setVisibility(View.VISIBLE);

        // 更新状态
        isCheckedIn = true;
        checkInButton.setText("已签到");
        checkInButton.setEnabled(false);
        checkOutButton.setEnabled(true);

        // 显示签到成功提示
        Toast.makeText(getActivity(), "签到成功", Toast.LENGTH_SHORT).show();

        // 保存签到记录到数据库
        saveAttendanceRecord(true, now, currentLocationTextView.getText().toString());
        
        // 保存状态到SharedPreferences
        saveAttendanceState();
    }
    
    /**
     * 执行签退操作
     */
    private void performCheckOut() {
        // 获取当前时间作为签退时间
        Date now = new Date();
        String checkOutTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(now);
        checkOutTimeTextView.setText("签退时间：" + checkOutTime);
        checkOutTimeTextView.setVisibility(View.VISIBLE);

        // 更新状态
        isCheckedOut = true;
        checkOutButton.setText("已签退");
        checkOutButton.setEnabled(false);
        
        // 签退后将签到按钮状态更新为"今日已完成打卡"
        checkInButton.setText("今日已完成打卡");
        checkInButton.setBackgroundResource(R.drawable.button_secondary);
        checkInButton.setEnabled(false);

        // 显示签退成功提示
        Toast.makeText(getActivity(), "签退成功", Toast.LENGTH_SHORT).show();

        // 保存签退记录到数据库
        saveAttendanceRecord(false, now, currentLocationTextView.getText().toString());
        
        // 保存状态到SharedPreferences
        saveAttendanceState();
    }
    
    /**
     * 保存打卡记录到数据库
     */
    private void saveAttendanceRecord(boolean isCheckIn, Date time, String location) {
        if (database != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 查询今日是否已有打卡记录
                        AttendanceRecord record = database.attendanceDao().getTodayAttendanceRecordSync(currentEmployeeId);
                        
                        if (record == null) {
                            // 创建新记录
                            record = new AttendanceRecord();
                            record.setEmployeeId(currentEmployeeId);
                            
                            if (isCheckIn) {
                                record.setCheckInTime(time);
                                record.setCheckInLocation(location);
                            } else {
                                record.setCheckOutTime(time);
                                record.setCheckOutLocation(location);
                                record.setCompleted(true);
                            }
                            
                            database.attendanceDao().insert(record);
                        } else {
                            // 更新现有记录
                            if (isCheckIn) {
                                record.setCheckInTime(time);
                                record.setCheckInLocation(location);
                            } else {
                                record.setCheckOutTime(time);
                                record.setCheckOutLocation(location);
                                record.setCompleted(true);
                            }
                            
                            database.attendanceDao().update(record);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }



    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，重新获取位置
                getCurrentLocation();
            } else {
                // 权限被拒绝，显示提示
                Toast.makeText(getActivity(), "需要位置权限才能获取当前位置", Toast.LENGTH_SHORT).show();
                currentLocationTextView.setText("当前位置：未授予位置权限");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 停止更新时间
        handler.removeCallbacksAndMessages(null);
    }
}